<template>
  <!--  v-loading="loading" -->
  <div element-loading-background="rgba(0, 0, 0, 0.8)"
       element-loading-text="拼命加载服务中。。">
    <!-- <div v-show="disconnect"
         @click="startReadIcCardThread"
         class="reload-ic-box">
      <div>
        设备连接不可用，点击重连...
      </div>
    </div> -->
    <component ref="activePage"
               :custom="$props.custom"
               :url="$props.url"
               :ic="$props.ic"
               :title="$props.title"
               :reasons="$props.custom.reasons"
               v-bind:is="$props.temp"
               @handleSuccess="handleSuccess"
               @showCard89Info="showCard89Info"
               @readCard="readCard"
               @customSentMqttMsg="customSentMqttMsg"
               @setForm="setForm"
               @logout="showPageHelper"></component>
    <LoginDialog ref="loginDialog"
                 @login="login"></LoginDialog>
    <PageHelper ref="pageHelper"
                @logout="logout"></PageHelper>

    <landing-page ref="landingPage"></landing-page>
  </div>
</template>
<script>
import { GSAConstants } from '@/utils/access'

import { ipcRenderer } from 'electron'
import axios from 'axios'
import {
  showSuccessMsg,
  showErrorMsg,
  showWarningMsg,
  showInfoMsg,
  showNotify,
  debugLog,
  log,
} from '@/utils/message'
import { getNetworkIp } from '@/utils/http'
import Temp1 from './Temp1'
import LoginDialog from '@/views/login/login-dialog'
import LandingPage from '@/components/LandingPage.vue'
import PageHelper from './page-helper'
import Temp2 from './Temp2'
import Temp3 from './Temp3'
import CarList from './car-list'
import ManualVehicleManager from './manual-vehicle-manager'
import Performance from '@/tools/performance'

export default {
  components: { Temp1, Temp2, Temp3, LoginDialog, PageHelper, CarList, ManualVehicleManager, LandingPage },
  props: {
    temp: {
      type: String,
      default: function () {
        return 'Temp1'
      }
    },
    title: {
      type: String,
      default: function () {
        return ''
      }
    },
    ic: {
      type: String,
      default: function () {
        return ''
      }
    },
    custom: {
      type: Object,
      default: function () {
        return {}
      }
    },
    url: {
      type: String,
      default: function () {
        return ''
      }
    },
    readID: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    autoCommit: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    closeReadCard: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    readIC: {
      type: Boolean,
      default: function () {
        return true
      }
    }
  },
  data () {
    return {
      loading: false,
      tipMessage: '',
      sendMqttMsgSeq: 0,
      readPauseTime: 10000,
      readIdCardThread: null,
      readIcCardThread: null,
      pauseReadCardThread: null,
      countdownThread: null,
      clearThread: null,
      isReadIdCard: false,
      isReadIcCard: false,
      errIc: false,
      errId: false,
      isReload: false,
      disconnect: false,
      healthDetectionThread: null,
      reloadCount: 0,
      isDown: false,
      lastSuccessCard: '',
      form: {
        name: '',
        idNo: '',
        tractorNo: '',
        saltIdNo: '',
        saltName: '',
        pccId: '',
        permitNo: '',
      },
      appConfigData: null,
    }
  },
  created () {
    setInterval(() => {
      log('core开始检查连接')
      ipcRenderer.send('send-mqtt-client-check')
    }, 60000)
  },
  mounted () {
    this.init()
    log('core.layout-------init--------')

    // 判断是否是osd， ssd
    if (this.$props.ic === GSAConstants().TOPIC_MANUAL_OSD.ic
      || this.$props.ic === GSAConstants().TOPIC_MANUAL_SSD.ic
      || this.$props.ic === GSAConstants().TOPIC_PREADVICE_MANUAL_OUT.ic) {
      this.loading = true

      // no login
      if (!this.$store.getters.loginFlag) {
        this.$nextTick(() => {
          this.$refs.loginDialog.show()
        })
      }
    }
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    console.log('core.layout关闭loading')
  },
  methods: {
    showCard89Info () {
      this.$emit("showCard89Info")
    },
    setForm (form) {
      this.form = { ...this.form, ...form }
    },
    // 渲染刷新页面c
    refreshPage () {
      this.doPageFun('setForm', this.form)
    },
    // 重连MQTT
    reConnection () {
      // if (this.isReload) {
      //   log('core.layout正在重连，防止重复重连， 重连down')
      //   return
      // }
      // this.isReload = true
      log('core.layout正在重连')
      this.closeMqttConnect()
      this.deviceAuthenticate(this.appConfigData)
    },
    // 开启健康检测
    refreshHealthDetection () {
      if (true) {
        return
      }
      if (this.healthDetectionThread) {
        clearInterval(this.healthDetectionThread)
      }

      this.startHealthDetection = setInterval(() => {
        const form = {}
        this.sendMqttMsgSeq += 1
        form.ip = getNetworkIp()
        let message = {
          dt: form,
          ic: GSAConstants().TOPIC_HEART.ic,
          sn: this.appConfigData.deviceSerialNo,
          id: this.sendMqttMsgSeq,
          en: false,
        }
        ipcRenderer.send('send-mqtt-client-message', GSAConstants().TOPIC_HEART.url, message)
      }, 10000)
    },
    // 挂载监听
    registerListener () {
      log('core.layout开始注销事件')
      ipcRenderer.removeAllListeners()

      ipcRenderer.on('init-com-reply', (event, res) => {
        log('串口初始化结果', res)

        if (res.code === -777) {
          setTimeout(() => {
            log('重新初始化串口')
            this.showMsg('串口不可用，串口正在重连', 'error')
            ipcRenderer.send('init-com', this.appConfigData.readIcPort, this.$store.getters.terminalDtl.iccardType)
          }, 2000);
        }
      })

      log('core.layout开始挂载监听事件')
      ipcRenderer.on('send-mqtt-client-check-reply', (event, res) => {
        if (res === 200) {
          log('客服端正常, 心跳正常.')
        } else {
          log('检测到客户端未连接， 执行重连')
          this.reConnection()
        }
      })
      // send - mqtt - client - check
      ipcRenderer.on('start-mqtt-connect-reply', (event, res) => {
        log('core.layout====start-mqtt-connect-reply====', res)
        this.$refs.loginDialog.loading = false
        // 关闭重连标识
        this.isReload = false

        // 重置表单
        this.isReadIcCard = false
        this.isReadIdCard = false
        this.resetFormObject()
        this.doPageFun('connectSuccess', res)
        // debugLog(res, 'core.layoutMQTT链接结果')
      })
      //注册业务返回监听器
      ipcRenderer.on('send-mqtt-client-message-reply', (event, res) => {
        log('core.layoutcore.layout===send-mqtt-client-message-reply===')
        if ('客户端未连接' === res) {
          // showErrorMsg('检测到客户端断开连接， 三秒开始重新连接。')
          // setTimeout(() => {
          //   ipcRenderer.send('restart')
          // }, 3000)
          this.reConnection()
          // this.appConfigData = false
        }
        debugLog(res)
      })

      ipcRenderer.on('read-app-config-reply', (event, res) => {
        log('core.layouttread-app-config-reply')
        this.appConfigData = JSON.parse(res.data)
        this.startMqttConnect()
      })

      ipcRenderer.on('mqtt-server-message-topic', (event, res) => {
        log('core.layout===mqtt-server-message-topic===')

        this.handleMqttMessage(res)
      })

      ipcRenderer.on('mqtt-heart-send', (event, res) => {
        log('core.layout==发包===', res)

        if (res.cmd.indexOf('connect') > -1) {
          // this.showMsg('服务器正在重连', 'error')
          this.showMsg('服务不可用，服务正在重连', 'error')
          log('core.layout服务不可用，服务正在重连')
        }
      })

      ipcRenderer.on('mqtt-heart-receive', (event, res) => {
        log('core.layout==收包===', res.cmd)
        this.reloadCount++


      })

      // 加载dll
      ipcRenderer.on('load-card-dll-thread-reply', (event, res) => {
        log('core.layoutload-card-dll-thread-reply 读卡服务启动成功')
        this.startReadIdCardThread()
        this.startReadIcCardThread()
        this.$message({
          message: '读卡服务启动成功',
          type: 'success'
        })
      })

      ipcRenderer.on('close-mqtt-connect-reply', (event, res) => {
        log('core.layoutclose-mqtt-connect-reply')
        log(res)
      })
      this.registerReadListener()

      // 子页面如果有
      this.doPageFun('registerListener')
    },
    updateExe () {
      if (!this.appConfigData.updateUrl) {
        console.log('core.layout未在配置文件中检测到更新的远程地址，停止更新')
        return
      }
      this.$refs.landingPage.CheckUpdate('one')
    },
    init () {
      // setTimeout(() => {
      //   this.startMqttConnect()
      // }, 2000)
      this.appConfigData = this.$store.getters.config

      this.registerListener()
      // update
      this.updateExe()

      this.disconnect = false
      // 不开启读卡线程
      if (!this.$props.closeReadCard) {
        setTimeout(() => {
          //  加载dll
          this.initReadThread()
        }, 6000)
      }

      console.log('开始初始化读卡串口')
      ipcRenderer.send('init-com', this.appConfigData.readIcPort, this.$store.getters.terminalDtl.iccardType)

      window.setInterval(() => {
        Performance.startExecute(`检测内存 ===》 `)(); /// 路由性能监控
      }, 6000)
    },
    showPageHelper () {
      this.$nextTick(() => {
        this.$refs.pageHelper.show(this.$props.ic)

      })
    },
    // 登陆验证的方法
    login (form) {
      this.sendMqttMsgSeq += 1
      form.ip = getNetworkIp()
      let message = {
        dt: form,
        ic: GSAConstants().TOPIC_LOGIN.ic,
        sn: this.appConfigData.deviceSerialNo,
        id: this.sendMqttMsgSeq,
        en: false,
      }
      log('core.layoutlogin :' + JSON.stringify(form))
      debugLog(message, '请求MQTT信息')
      ipcRenderer.send('send-mqtt-client-message', GSAConstants().TOPIC_LOGIN.url, message)

      this.refreshHealthDetection()
    },
    // logout
    logout () {
      this.$store.commit('LOGIN_FLAG', false)

      log('core.layoutlogout')
      // 展示登陆页面
      this.$nextTick(() => {
        this.$refs.loginDialog.show()
      })
    },
    resetFormObject () {
      log('core.layoutresetFormObject')
      this.form = {
        name: '',
        idNo: '',
        pccId: '',
        tractorNo: '',
        saltIdNo: '',
        saltName: '',
        permitNo: '',
      }
      this.doPageFun('setForm', this.form)
      this.doPageFun('showMsg', { msg: '请刷卡......' })

      // 重置读卡线程
      this.isReadIcCard = false
      this.isReadIdCard = false

    },
    // 开启读ID卡线程
    startReadIdCardThread () {
      if (!this.$props.readID) {
        debugLog('core.layout不读ID卡， ID线程停止', '读卡信息')
        return
      }
      this.readIdCardThread = window.setInterval(() => {
        if (!this.isReadIdCard) {
          ipcRenderer.send('read-id-card')
        }
      }, 2000)
      window.readIdCardThread = this.readIdCardThread
    },
    // 手动读卡
    readCard (type) {
      if (type === 'ic') {
        // ipcRenderer.send('read-ic-card', this.appConfigData.readIcPort, this.$store.getters.terminalDtl.iccardType, no_halt)
        ipcRenderer.send('read-ic-card', this.appConfigData.readIcPort, this.$store.getters.terminalDtl.iccardType, 1)
      } else {
        ipcRenderer.send('read-id-card', null, this.$store.getters.terminalDtl.iccardType)
      }
    },
    // 开启读IC卡线程
    startReadIcCardThread () {
      if (!this.$props.readIC) {
        debugLog('core.layout不读IC卡， IC线程停止', '读卡信息')
        return
      }
      this.disconnect = false
      debugLog('core.layout开始读 read-ic-card', '读卡信息')
      this.readIcCardThread = window.setInterval(() => {
        if (!this.isReadIcCard) {
          //  === 
          let no_halt = 0;
          if (GSAConstants().TOPIC_PREADVICE_GATE_OUT_CHECK.ic === this.$props.ic) {
            no_halt = 1;
          }
          if (GSAConstants().TOPIC_PREADVICE_MANUAL_OUT.ic === this.$props.ic) {
            no_halt = 1;
          }
          log('发送读卡请求')
          ipcRenderer.send('read-ic-card', this.appConfigData.readIcPort, this.$store.getters.terminalDtl.iccardType, no_halt)
        }
      }, 2000)

      // ipcRenderer.send('read-ic-card', this.appConfigData.readIcPort, this.$store.getters.terminalDtl.iccardType, 1)
      // ipcRenderer.send('read-ic-card', 2, this.$store.getters.terminalDtl.iccardType)

      window.readIcCardThread = this.readIcCardThread
    },
    // 暂停读身份证
    pauseReadIdCard () {
      this.isReadIdCard = true
      //清空倒计时
      this.clearCountdownThread()
      // 读卡成功后暂停  如果ic卡的状态也是暂停说明就可以提交了
      if (!this.isReadIcCard && this.$props.readIC) {
        this.readCardCountdown('请刷PCC卡')
      } else {
        // 自动提交
        if (!this.$props.autoCommit) {
          return
        }
        this.showMsg('正在处理， 请稍后')
        this.sendMqttMessage()
      }
    },
    pauseReadIcCard () {
      this.isReadIcCard = true
      //清空倒计时
      this.clearCountdownThread()

      if (!this.isReadIdCard && this.$props.readID) {
        this.readCardCountdown('请刷身份证')
      } else {
        // 自动提交
        if (!this.$props.autoCommit) {
          return
        }
        this.showMsg('正在处理， 请稍后')
        // this.sendMqttMessage()
      }
    },
    commit () {
      if (!this.$props.autoCommit) {
        return
      }
      if (!this.isReadIdCard && this.$props.readID) {
        // this.readCardCountdown('请刷身份证')
        return false
      }
      if (!this.isReadIcCard && this.$props.readIC) {
        // this.readCardCountdown('请刷PCC卡')
        return false
      }
      this.sendMqttMessage()
    },
    readCardCountdown (msg) {
      var count = 10
      this.clearCountdownThread()

      this.countdownThread = window.setInterval(() => {
        count--
        this.showMsg(
          msg + '......      超时倒计时 : ' + count + ' sec.'
        )
        if (count <= 1) {
          this.timeoutHandle()
        }
      }, 1000)
    },
    clearCountdownThread () {
      if (this.countdownThread) {
        window.clearInterval(this.countdownThread)
      }
    },
    timeoutHandle () {
      this.clearCountdownThread()
      this.showMsg('处理超时...')
      log('core.layout超时清空表单')
      setTimeout(() => {
        this.resetReadThread()
      }, 1000)
    },
    //初始化读卡服务
    initReadThread () {
      log('core.layout初始化读卡服务')
      //重启服务
      setTimeout(() => {
        this.loadCardDll()
      }, 2000)
    },
    resetReadThread () {
      window.setTimeout(() => {
        this.resetFormObject()
        debugLog('core.layout恢复读卡服务')
      }, 10000)
    },
    //  =====start===读卡操作=====
    // 初始化加载dll
    loadCardDll () {
      log('core.layout==== loadCardDll ====')
      this.$message({
        message: '正在加载系统文件',
        type: 'info'
      })
      ipcRenderer.send('load-card-dll-thread')
      // ipcRenderer.send('load-test-dll-thread')
    },
    // 注册ID和IC卡消息监听器
    registerReadListener () {

      // 注册ID卡消息监听器
      ipcRenderer.on('read-id-card-reply', (event, res) => {
        // 返回读卡接口 -999 返回0能读取到信息  返回 2代表设备链接，但是找不到卡   返回1代表设备没有连接 因为有中文所以要转码  111
        this.doPageFun('readIdReply', res)
        if (res.readCode === 1) {
          // 读卡成功
          debugLog('core.layout身份证读取成功')
          this.form.name = res.name
          this.form.idName = res.name
          // this.form.driverName = res.namef
          this.form.idNo = res.idNo
          this.form.driverCardId = res.idNo
          this.form.saltIdNo = res.saltIdNo
          this.form.saltName = res.saltName
          this.doPageFun('setForm', this.form)
          this.doPageFun('readIdCardSuccess', res)
          this.showMsg('身份证读取成功')


          //暂停读取ID卡线程
          this.pauseReadIdCard()
        } else if (res.readCode === -777) {
          this.errId = true
          this.showMsg('身份证读卡器未连接，请检查设备', 'error')
          log('core.layout身份证读卡器未连接，请检查设备')
        } else if (res.readCode === 2) {
          if (this.errId) {
            this.errId = false
            this.showMsg('请刷卡......')
          }
          // log('core.layout等待刷身份证')
        } else {
          log(res)
        }
        // debugLog(msgInfo, '读卡信息')
      })
      // 注册IC卡消息监听器
      ipcRenderer.on('read-ic-card-reply', (event, res) => {
        // log('core.layout====read-ic-card-reply====')
        log('core.layout读IC卡， 返回Code', res)
        let msgInfo = JSON.stringify(res)
        // log(msgInfo)
        this.doPageFun('readIcReply', res)
        if (res.readCode == 1) {
          this.form.pccId = res.cardNo
          this.form.permitNo = res.permitNo
          this.doPageFun('setForm', this.form)
          this.doPageFun('readIcCardSuccess', res)
          this.$emit('readIcCardSuccess', this.form)

          this.showMsg('PCC卡读取成功')
          log('core.layout====getTractorNo====', res.permitNo)
          this.getTractorNo(res.permitNo)
          this.pauseReadIcCard()

          log('core.layout====PCC卡读取成功')
        } else if (res.readCode === -777) {
          // 暂停读卡
          if (this.readIcCardThread) {

            clearInterval(this.readIcCardThread)
            this.disconnect = true
          }
          this.errIc = true
          setInterval(() => {
            this.showMsg('港运通读卡器未连接，请检查设备, 然后重启客户端', 'error')
          }, 500)
          log('core.layout港运通读卡器未连接，请检查设备, 然后重启客户端')
        } else if (res.readCode === 3) {
          this.showMsg('刷卡频繁，请重新放卡！', 'error')
          log('刷卡频繁，请重新放卡！', 'error')
        }
        else if (code === -222 || code === -333 || code === -401) {
          log('core.layoutPPC无效', 'error')
          this.showMsg('卡不可识别！', 'error')
        } else if (res.readCode === 2) {
          this.lastSuccessCard = ''
          if (this.errIc) {
            this.errIc = false
            this.showMsg('请刷卡......')
          }
          // log('core.layout等待刷卡')
        } else if (res.readCode === -999) {
          this.showMsg(res.msg, 'error')
        } else {
          // log(msgInfo)
        }
      })

      // ipcRenderer.on("UpdateMsg", (event, age) => {
      //   switch (age.state) {
      //     case -2:
      //       console.log(age.msg)
      //       break
      //     case -1:
      //       console.log('core.layout自动更新程序更新发生了错误， 访问的Http接口为：', this.$store.getters.config.updateUrls)
      //       break;
      //     case 0:
      //       console.log('core.layout自动更新程序正在检查更新， 访问的Http接口为：', this.$store.getters.config.updateUrl)
      //       break;
      //     case 1:
      //       console.log('core.layout已检查到新版本，开始下载')
      //       break;
      //     case 2:
      //       console.log('core.layout无新版本')
      //       break;
      //     case 3:
      //       break;
      //     case 4:
      //       console.log('core.layout更新下载完成！')
      //       break;
      //     default:
      //       break;
      //   };
      // })
      // while (true) {
      // this.test()
      // }
    },
    // =====end===读卡操作=====
    // =====start===MQTT=====
    deviceAuthenticate (queryObject, icount) {
      if (icount == undefined) {
        icount = 0;
      }
      if (icount > 1) {
        return;
      }

      this.$message({
        message: '正在连接服务器',
        duration: 10000,
        type: 'info'
      })
      log('core.layout开始注册设备', queryObject)
      axios
        .post(queryObject.eipUrl + '/api/deviceAuthenticate', queryObject, {
          timeout: 10000,
        })
        .then((res) => {
          // var resObj = JSON.parse(res)
          var ret = res.data
          if (ret.result && ret.result === 'success') {
            log('core.layout===设备注册成功===')
            this.loading = false
            this.$message({
              message: '设备注册成功',
              type: 'success'
            })
            debugLog(ret, '设备注册')
            this.appConfigData.sessionId = ret.data.sessionId
            this.appConfigData.serviceInstanceIpAddress =
              ret.data.serviceInstanceIpAddress
            this.appConfigData.serviceInstanceMqttPort =
              ret.data.serviceInstanceMqttPort

            this.$store.commit('SET_APP_CONFIG', queryObject)
            this.connectMqtt(this.appConfigData)
          } else {
            // log('core.layout错误注册设备', res)
            // showErrorMsg(res.data.message)
            this.$message({
              message: '设备注册异常, 正在重连',
              duration: 10000,
              type: 'error'
            })

            // this.reloadDeviceAuthenticate(this.appConfigData, icount)
          }
        })
        .catch((error) => {
          // showErrorMsg(error, 'URL：', queryObject.eipUrl + '/api/deviceAuthenticate')
          // this.reloadDeviceAuthenticate(this.appConfigData)
          // this.showMsg('系统超时', 'error')
          log('注册设备异常！', error)
        })
    },
    reloadDeviceAuthenticate (queryObject, icount) {
      setTimeout(() => {
        if (icount == undefined) {
          icount = 0;
        }
        this.deviceAuthenticate(queryObject, icount++)
      }, 10000)
    },
    setCustAttr (attr, value) {
      this[attr] = value
    },
    // 子页面核心信息切换的方法
    showMsg (msg, type) {
      this.doPageFun('showMsg', { msg: msg, type: type })

      this.$forceUpdate()
    },
    // 启动 MQTT服务器连接
    startMqttConnect () {
      // 只有认证通过loading 才会打开
      this.loading = true;
      if (!this.appConfigData) {
        this.readAppConfig()
      } else {
        setTimeout(() => {
          if (this.appConfigData) {
            log('core.layout========appConfigData========')
            log(this.appConfigData)
            this.deviceAuthenticate(this.appConfigData)
          }
        }, 2000)
      }
    },
    connectMqtt (mqttObject) {
      log('core.layoutstartMqttConnect')
      debugLog(mqttObject, 'MQTT连接信息')
      ipcRenderer.send('start-mqtt-connect', mqttObject)
    },
    // 关闭 MQTT服务器
    closeMqttConnect () {
      log('core.layoutcloseMqttConnect')
      ipcRenderer.send('close-mqtt-connect')
    },
    // 发送MQTT消息
    sendMqttMessage () {
      this.sendMqttMsgSeq += 1
      let message = {
        dt: {
          idInfo: {
            idNu: this.form.idNo,
            name: this.form.name,
          },
          handlerType: 'checkCard',
          userInfo: this.$store.getters.userInfo,
          nGenFullTractorNo: '',
          tcCode: this.form.permitNo,
          ip: getNetworkIp(),
          cardId: this.form.pccId,
        },
        ic: this.$props.ic,
        sn: this.appConfigData.deviceSerialNo,
        id: this.sendMqttMsgSeq,
        en: false,
      }
      debugLog(message, '请求MQTT信息')
      log('core.layoutsend-mqtt-client-message url：' + this.$props.url + JSON.stringify(message))
      ipcRenderer.send('send-mqtt-client-message', this.$props.url, message)
    },
    customSentMqttMsg (url, msg, noneMsg) {
      this.sendMqttMsgSeq += 1
      msg.id = this.sendMqttMsgSeq
      msg.sn = this.appConfigData.deviceSerialNo
      msg.ip = getNetworkIp()
      debugLog(msg, '请求MQTT信息')
      log('core.layoutsend-mqtt-client-message url：' + url + JSON.stringify(msg))
      log('core.layoutcustomSentMqttMsg 请求MQTT信息 msg:', msg, 'url:', url)

      if (msg.dt) {
        msg.dt.userInfo = this.$store.getters.userInfo
      }
      ipcRenderer.send('send-mqtt-client-message', url, msg)

      if (!noneMsg) {
        this.showMsg('正在处理， 请稍后')
      }
      // 刷新心跳
      this.refreshHealthDetection()
    },
    // 获取车牌号
    getTractorNo (permitNo) {
      log('core.layout====getTractorNo 开始加载车牌号 ====', permitNo)

      this.sendMqttMsgSeq += 1
      let message = {
        dt: {
          permitNo: permitNo,
          ip: getNetworkIp(),
        },
        ic: GSAConstants().TOPIC_PREADVICE_CAR_NUMBER.ic,
        sn: this.appConfigData.deviceSerialNo,
        id: this.sendMqttMsgSeq,
        en: false,
      }
      log('core.layout------ 发送消息请求 log' + JSON.stringify(message))
      ipcRenderer.send('send-mqtt-client-message', GSAConstants().TOPIC_PREADVICE_CAR_NUMBER.url, message)
      this.refreshHealthDetection()
    },
    // MQTT后端业务返回消息处理方法
    handleMqttMessage (mqttMessage) {
      //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":1,"dt":["192764","zxc","","y|GD|BW8337|",""]}
      if (!mqttMessage) {
        log('core.layouthandleMqttMessage ----> 异常， 没有返回值')
        return
      }
      log('core.layout------ handleMqttMessage' + JSON.stringify(mqttMessage))

      var messageObject = JSON.parse(mqttMessage)

      // 获取车牌号
      if (messageObject.ic === GSAConstants().TOPIC_PREADVICE_CAR_NUMBER.ic) {
        this.doPageFun('getCarNumberReply', messageObject)
      }
      if (messageObject.rc && messageObject.rc === 1) {
        log('core.layoutRC 1 ---->')
        // 获取车牌号
        if (messageObject.ic === GSAConstants().TOPIC_PREADVICE_CAR_NUMBER.ic) {
          this.writePccInfo(messageObject.dt)
          log(JSON.stringify(messageObject) + '读取车牌信息成功！')
          this.doPageFun('showMsg', { msg: '读取PCC卡信息成功！', type: '' })
          this.commit()
          return
        }
        if (messageObject.ic === GSAConstants().TOPIC_LOGIN.ic) {
          log(JSON.stringify(messageObject) + '登陆成功！')
          this.loginSuccess(messageObject)
          return
        }

        // 对外部通知消息处理成功
        this.$emit('handleSuccessMqttMessage', messageObject)
        this.doPageFun('handleSuccessMqttMessage', messageObject)
      } else if (messageObject.rc) {
        if (messageObject.ic === GSAConstants().TOPIC_LOGIN.ic) {
          log(messageObject, '登陆失败！')
          this.$message.error(messageObject.rm)
          this.$refs.loginDialog.loading = false
          return
        }
        if ('out:' + GSAConstants().TOPIC_PREADVICE_MANUAL_OUT.ic === messageObject.ic) {
          // 如果是放行，写卡的错误信息不显示 
          this.doPageFun('handleErrorMqttMessage', messageObject)
          this.$emit('handleErrorMqttMessage', messageObject)
          return
        }
        if (GSAConstants().TOPIC_PREADVICE_MANUAL_OUT.ic === messageObject.ic) {
          // 如果是放行，写卡的错误信息不显示 
          this.doPageFun('handleErrorMqttMessage', messageObject)
          this.$emit('handleErrorMqttMessage', messageObject)
          return
        }

        if (messageObject.ic === GSAConstants().TOPIC_PREADVICE_CAR_NUMBER.ic) {
          // 车牌读错误， 重置表单
          this.handleSuccess()
        }
        this.doPageFun('handleErrorMqttMessage', messageObject)
        this.$emit('handleErrorMqttMessage', messageObject)
        //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":26,"rm":"未知的读卡器错误"}
        this.showMsg(messageObject.rm, 'error')
      } else {
        this.showMsg('未知错误，请联系管理员。', 'error')
      }
    },
    // 成功清理表单
    handleSuccess () {
      log('core.layout启动倒计时10s， 清理表单')
      // reset 读卡
      if (this.clearThread) {
        clearTimeout(this.clearThread)
      }
      this.clearThread = setTimeout(() => {
        this.isReadIcCard = false
        this.isReadIdCard = false
        this.resetFormObject()
      }, 10000);
    },
    /**
     * 写PCC的回调
     */
    writePccInfo (dt) {
      this.form.tractorNo = dt.tractorNo
      this.form.driverCardId = dt.idNo
      this.form.returnReceiptId = dt.returnReceiptId
      this.form.idName = dt.driverName
      this.form.hasPcc = true
      this.form.manTel = dt.manTel
      this.form.companyName = dt.companyName
      this.form.driverName = dt.driverName
      this.form.vehicleColor = dt.tidNgenColor
      this.form.vehiclePy = dt.tidNgenPy
      this.form.vehicleKey = dt.tidNgenKey
      this.form.vehicleSuf = dt.tidNgenSuf
      this.doPageFun('setForm', this.form)
    },
    // 执行子页面的函数
    doPageFun (funName, args) {
      const page = this.$refs.activePage
      if (!page || !page[funName]) {
        // 页面或函数不存在
        return
      }

      // 执行方法
      page[funName](args)
    },
    // 登陆成功的业务
    loginSuccess (ret) {
      this.$refs.loginDialog.close()

      // 回写用户信息 
      this.$store.commit('SET_INFO', ret.dt)
      this.$store.commit('LOGIN_FLAG', true)
      log('core.layout--- 测试读取用户消息 ---', this.$store.getters.userInfo)

      if (ret.dt) {
        ret.dt.menus.forEach(menu => {
          menu.key = menu.idKey
        })
        this.$store.commit('SET_MENUS', ret.dt.menus)
      }

      this.$nextTick(() => {
        this.$refs.pageHelper.show(this.$props.ic)
      })


      // 刷新权限
      this.$emit('refreshMenus')
    },
    // =====start===注册业务，也是测试用=====
    readAppConfig () {

      ipcRenderer.send('read-app-config', '读取本地文件的配置文件')
    },
  },
}
</script>

<style scoped>
.reload-ic-box {
  height: 80px;
  width: 251px;
  -moz-box-shadow: 2px 1px 1px #333333;
  -webkit-box-shadow: 2px 1px 1px #333333;
  box-shadow: 2px 1px 1px #e3baba;
  border-radius: 5px;
  color: #f9f9f9;
  z-index: 20;
  text-align: center;
  right: 370px;
  line-height: 50px;
  font-weight: bold;
  /* text-align: center; */
  padding: 10px;
  background-color: #ff0b0b;
  position: absolute;
  top: 300px;
  font-size: 14px;
}
</style>
